<template>
  <div>
    <diagtime-view v-if="pop.diagnose.showMe" ref="refDiagoseView" @closed="handleHideDiagTimeView"></diagtime-view>
    <div v-else>
      <div class="diagnose_search_bar">
        <region-select
          v-if="isShowSalonSelect"
          ref="refSalonSelect"
          :mode="2"
          :dept="2"
          :display="'row'"
          @selected="handleSalonSelected"></region-select>
        <el-input
          v-model="search.diagnoseNo"
          size="mini"
          clearable
          style="width: 240px"
          placeholder="模糊查询复盘单号, 如: 2502"></el-input>
        <el-button v-if="listLoading" type="primary" icon="el-icon-loading" plain size="mini" disabled>搜索</el-button>
        <el-button v-else type="primary" icon="el-icon-search" plain size="mini" @click.stop="loadDiagnoseHis">
          搜索
        </el-button>
      </div>
      <el-table
        ref="refDiagnoseTable"
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        @selection-change="handleSelectionChange">
        <el-table-column fixed prop="createDate" label="创建日期" align="center" width="120">
          <template slot-scope="{ row }">{{ row.createDate ? row.createDate.substring(0, 11) : '--' }}</template>
        </el-table-column>
        <el-table-column
          fixed
          prop="diagnoseNo"
          label="复盘单号"
          align="center"
          width="180"
          show-overflow-tooltip></el-table-column>
        <el-table-column
          fixed
          prop="coachName"
          label="教练名称"
          align="center"
          width="100"
          show-overflow-tooltip></el-table-column>
        <el-table-column
          prop="salonName"
          label="门店名称"
          align="center"
          width="180"
          show-overflow-tooltip></el-table-column>
        <el-table-column prop="salonScale" label="门店规模" align="center" width="100" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ getBaseEnumName(row.salonScale, 'salonSize') }}
          </template>
        </el-table-column>
        <el-table-column prop="salonAttribute" label="门店属性" align="center" width="100" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ getBaseEnumName(row.salonAttribute, 'salonAttr') }}
          </template>
        </el-table-column>
        <el-table-column prop="salonType" label="门店类型" align="center" width="100" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ getBaseEnumName(row.salonType, 'salonType') }}
          </template>
        </el-table-column>
        <el-table-column prop="businessEnvironment" label="商圈环境" align="center" width="100" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ getBaseEnumName(row.businessEnvironment, 'businessEnvironment') }}
          </template>
        </el-table-column>
        <el-table-column prop="mainCompetition" label="主要竞争力" align="center" width="100" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ getBaseEnumName(row.mainCompetition, 'salonCompetitiveness') }}
          </template>
        </el-table-column>
        <el-table-column prop="subCompetition" label="次要竞争力" align="center" width="100" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ getBaseEnumName(row.subCompetition, 'salonCompetitiveness') }}
          </template>
        </el-table-column>
        <el-table-column prop="mainDefect" label="主要缺陷" align="center" width="100" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ getBaseEnumName(row.mainDefect, 'salonCompetitiveness') }}
          </template>
        </el-table-column>
        <el-table-column prop="subDefect" label="次要缺陷" align="center" width="100" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ getBaseEnumName(row.subDefect, 'salonCompetitiveness') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="lastDecorationTime"
          label="装修时间"
          align="center"
          width="100"
          show-overflow-tooltip></el-table-column>
        <el-table-column
          prop="operationStartTime"
          label="启动时间"
          align="center"
          width="100"
          show-overflow-tooltip></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="160">
          <template slot="header">
            <el-link type="success" style="margin-right: 5px" @click.stop.native="handleShowTimeline">
              复盘时间线
            </el-link>
          </template>
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              size="mini"
              plain
              style="margin: 0 5px 0 0"
              @click.stop.native="handleShowDiagTimeView(row)">
              详情
            </el-button>
            <el-popover placement="left" width="220">
              <p>这将彻底删除本次复盘的所有数据, 确定要删除吗?</p>
              <div style="text-align: right; margin: 0">
                <el-button type="primary" size="mini" @click="goDelDiagnoseBase(row)">确定</el-button>
              </div>
              <el-button slot="reference" type="danger" size="mini" plain>删除</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="loadDiagnoseHis"></pagination>
    </div>

    <el-drawer :visible.sync="pop.timeline.showMe" :with-header="false" direction="rtl" size="30%">
      <diag-timeline ref="refDiagTimeline"></diag-timeline>
    </el-drawer>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import { delBaseDiagnose, getBaseDiagnosePage, getBaseEnums } from '@/api/diagnose';
import { getSalon } from '@/api/txs';
// 引入自定义组件
import Pagination from '@/components/Pagination';
import '@/utils/datefmt';
import { isAdminRole, isCoachRole } from '@/utils/enum/roles';
import RegionSelect from '@/views/salon/RegionSelect.vue';
import DiagTimeView from './diagnose/index.vue';
import DiagTimeline from './diagnose/pop/timeline.vue';
// 引入第三方组件
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

export default {
  name: 'DiagnoseList',
  components: {
    Pagination,
    ['diag-timeline']: DiagTimeline,
    ['diagtime-view']: DiagTimeView,
    ['region-select']: RegionSelect,
  },
  filters: {},
  data() {
    return {
      salon: {}, // {salonId: '', salonNo: '', salonName: '', diagnoseNo: ''}
      baseEnums: {},
      list: [], // 页面 table 数据
      total: 0,
      listQuery: { page: 1, limit: 10 },
      ops: { isDeleting: false },
      listLoading: false, // 页面数据加载中?
      search: { diagnoseNo: '' },
      pop: {
        timeline: {
          showMe: false,
        },
        diagnose: {
          showMe: false,
        },
      },
    };
  },
  computed: {
    ...mapGetters(['name', 'id', 'deptId', 'openId']),
    isShowSalonSelect() {
      return isAdminRole(this.deptId) || isCoachRole(this.deptId);
    },
  },
  created() {
    this.loadSalonInfo();
    this.loadBaseEnums();
  },
  mounted() {
    if (!this.isShowSalonSelect) {
      this.salon.salonId = this.openId;
      this.loadDiagnoseHis();
    }
  },
  methods: {
    handleSelectionChange(val) {},
    handleSalonSelected: async function (salon) {
      if (salon) {
        this.salon.salonId = salon.salonId;
        this.salon.salonNo = salon.salonCode;
        this.salon.salonName = salon.salonName;
        this.loadDiagnoseHis();
      }
    },
    handleShowTimeline: async function () {
      this.pop.timeline.showMe = true;
      await this.$nextTick();
      this.$refs.refDiagTimeline.loadDiagnoseData(this.salon);
    },
    handleShowDiagTimeView: async function (row) {
      this.salon.diagnoseNo = row.diagnoseNo;
      this.pop.diagnose.showMe = true;
      await this.$nextTick();
      const cpy = Object.assign({}, row);
      this.$refs.refDiagoseView.loadDiagnoseData(cpy);
    },
    handleHideDiagTimeView() {
      this.pop.diagnose.showMe = false;
    },
    loadSalonInfo: function () {
      if (!this.salon.salonId) {
        return;
      }
      const errAlertMsg = '加载门店信息失败';
      getSalon(this.salon.salonId)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret) {
            this.salon.salonId = ret.id;
            this.salon.salonNo = ret.code;
            this.salon.salonName = ret.sname;
          }
        })
        .catch(err => {
          console.log('getSalon', err);
          MessageBox.alert(errAlertMsg);
        });
    },
    loadBaseEnums: async function () {
      const errAlertMsg = '查询类型失败';
      getBaseEnums()
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret) {
            this.baseEnums = Object.assign({}, ret);
          }
        })
        .catch(err => {
          console.log('loadBaseEnums', err);
          MessageBox.alert(errAlertMsg);
        });
    },
    loadDiagnoseHis: async function () {
      if (!this.salon.salonId) {
        // 不属于任何门店的用户(通常是系统管理员)
        return;
      }
      this.listLoading = true;
      const page = this.listQuery.page;
      const size = this.listQuery.limit;
      const diagnoseNo = this.search.diagnoseNo;
      const errAlertMsg = '查询历史复盘信息失败';
      await getBaseDiagnosePage(page, size, this.salon.salonId, !!diagnoseNo ? diagnoseNo : null)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.list.splice(0, this.list.length);
          this.list.push(...res.data.data.records);
          this.total = res.data.data.total;
        })
        .catch(err => {
          console.log('getBaseDiagnosePage', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    getBaseEnumName: function (val, attrName) {
      const e = this.baseEnums[attrName].find(x => x.code == val);
      if (e) {
        return e.name;
      }
      return '';
    },
    goDelDiagnoseBase: async function (row) {
      if (this.ops.isDeleting) {
        return;
      }
      this.ops.isDeleting = true;
      const errAlertMsg = '删除失败';
      await delBaseDiagnose(row.id)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          MessageBox.alert('删除成功');
          this.loadDiagnoseHis();
        })
        .catch(err => {
          console.log('delBaseDiagnose', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.ops.isDeleting = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/salonmodel.scss';

::v-deep .el-table td {
  padding: 5px 0;
  min-width: 0;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
}

.diagnose_search_bar {
  width: 100%;
  padding: 5px 16px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  gap: 5px;
}
</style>
